<template>
  <div class="login-page mx-auto p-3 w-330">
    <ValidateForm @form-submit="onFormSubmit">
      <div class="mb-3">
        <label for="exampleFormControlInput1" class="form-label"
          >邮箱地址</label
        >
        <ValidateInput
          v-model="emailVal"
          :rules="emailRules"
          @value="emailValue"
          placeholder="请输入正确的电子邮箱地址"
        ></ValidateInput>
      </div>
      <div class="mb-3">
        <label for="exmapleformControlTextarea1" class="form-label">密码</label>
        <ValidateInput
          v-model="passwordVal"
          :rules="passwordRules"
          placeholder="请输入密码"
          @value="passwordValue"
        ></ValidateInput>
      </div>
      <template #submit>
        <span class="btn btn-danger">登录</span>
      </template>
    </ValidateForm>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import ValidateForm from "@/components/ValidateForm.vue";
import ValidateInput, { RulesProp } from "@/components/ValidateInput.vue";
import createMessage from "@/hooks/createMessage";

export default defineComponent({
  name: "LoginIndex",
  components: {
    ValidateForm,
    ValidateInput,
  },
  setup() {
    const emailVal = ref("111@test.com");
    const emailRules: RulesProp = [
      // 邮箱的规则，应该被这个东西所约束
      { type: "required", message: "电子邮箱地址不能为空" },
      { type: "email", message: "请输入正确的电子邮箱格式" },
    ];
    const passwordVal = ref("111111");
    const passwordRules: RulesProp = [
      { type: "required", message: "密码不能为空" },
    ];
    const emailValue = (val: string) => {
      emailVal.value = val;
    };
    const passwordValue = (val: string) => {
      passwordVal.value = val;
    };

    // 登录
    const store = useStore();
    const router = useRouter();
    const onFormSubmit = (result: boolean) => {
      if (result) {
        const payload = {
          email: emailVal.value,
          password: passwordVal.value,
        };

        // 发送登录
        store
          .dispatch("loginAndFecth", payload)
          .then(() => {
            createMessage("登录成功 2 秒后跳转到首页", "success", 2000);
            setTimeout(() => {
              router.push("/");
            }, 2000);
          })
          .catch((e) => {
            console.log(e);
          });
      }
    };
    return {
      emailRules,
      emailVal,
      emailValue,
      onFormSubmit,
      passwordVal,
      passwordRules,
      passwordValue,
    };
  },
});
</script>

<style>
.w-330 {
  max-width: 330px;
}
</style>
